#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
void HeapInit(Heap* hp)
{
	assert(hp);
	hp->a = NULL;
	hp->size = 0;
	hp->capacity = 0;
}
void HeapDestroy(Heap* hp)
{
	assert(hp);
	free(hp->a);
	hp->a = NULL;
	hp->size = 0;
	hp->capacity = 0;
}
void swap(HeapDatatype* p1, HeapDatatype* p2)
{
	HeapDatatype tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
Adjustup(HeapDatatype *a,int child)
{
	assert(a);
	int parent = (child - 1) / 2;
	while (child>0)
	{
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HeapPush(Heap* ph,HeapDatatype x)
{
	assert(ph);
	if (ph->size == ph->capacity)
	{
		int newcapacity = ph->capacity == 0 ? 4 : ph->capacity * 2;
		HeapDatatype* tmp = (HeapDatatype*)realloc(ph->a, sizeof(HeapDatatype) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ph->capacity = newcapacity;
		ph->a = tmp;
	}
	ph->a[ph->size] = x;
	ph->size++;
	Adjustup(ph->a, ph->size - 1);
}
AdjustDown(HeapDatatype*a,int n,int parent)
{
	assert(a);
	int child = parent * 2 + 1;
	while (child<n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
		{
			child++;
		}
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HeapPop(Heap* ph)
{
	assert(ph);
	assert(!HeapEmpty(ph));
	swap(&ph->a[0],&ph->a[ph->size - 1]);
	ph->size--;
	AdjustDown(ph->a, ph->size, 0);
}
bool HeapEmpty(Heap* ph)
{
	assert(ph);
	return ph->size == 0;
}
HeapDatatype Heaptop(Heap* ph)
{
	assert(ph);
	assert(!HeapEmpty(ph));
	return ph->a[0];
}
int HeapSize(Heap* ph)
{
	assert(ph);
	return ph->size;
}